namespace AltNetUK.Web
{
    using System;
    using System.Net;
    using System.Web;

    public sealed class WwwModule : IHttpModule
    {
        private static readonly Uri _www = new Uri("http://www.altnetuk.com/");

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(OnBeginRequest);
        }

        private void OnBeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            string host = app.Request.Headers["host"];

            if (!host.StartsWith("localhost:", StringComparison.OrdinalIgnoreCase))
            {
                if (!"www.altnetuk.com".Equals(host, StringComparison.OrdinalIgnoreCase))
                {
                    string location = new Uri(_www, new Uri(app.Request.Url.PathAndQuery, UriKind.Relative)).AbsoluteUri;
                    app.Response.StatusCode = (int)HttpStatusCode.MovedPermanently;
                    app.Response.AppendHeader("Location", location);
                    app.Response.Cache.SetCacheability(HttpCacheability.Public);
                    app.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(1));
                    app.Response.End();
                }
            }
        }
    }
}